// 封装axios

import axios, {
  AxiosError,
  AxiosInstance,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import { ElMessage } from "element-plus";
import qs from 'qs'; // 引入 qs 库

export enum PostHeadersType {
  form = "form-data",
  formurlencoded = "form-urlencoded",
}
// 定义接口响应类型
interface ApiResult<T> {
  data: T;
  msg: string;
  code: number;
}
const instance: AxiosInstance = axios.create({
  baseURL: process.env.API_URL ?? "",
  timeout: 5000,
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.error(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    ElMessage.success(response.data.msg)
    return response.data;
  },
  (error: AxiosError) => {
    const { response } = error;
    if (response) {
      switch (response.status) {
        case 401:
          // 未授权，可以跳转到登录页
          ElMessage.error("401 Unauthorized");
          break;
        case 403:
          // 禁止访问
          ElMessage.error("403 Forbidden");
          break;
        case 500:
          // 服务器错误
          ElMessage.error("500 Internal Server Error");
          break;
        default:
          console.error("Error:", response.status, response.statusText);
      }
    } else if (!response && error.request) {
      // 请求已发出，但没有收到响应
      console.error("No response received:", error.request);
    } else {
      // 其他错误
      console.error("Error:", error.message);
    }
    return Promise.reject(error);
  }
);

export const requests = {
  get<T, D>(url: string, params?: D): Promise<ApiResult<T>> {
    return instance.get<ApiResult<T>>(url, { params }) as unknown as Promise<ApiResult<T>>;
  },
  post<T, D>(
    url: string,
    data?: D,
    config?: PostHeadersType
  ): Promise<ApiResult<T>> {
    let headers = { "Content-Type": "application/json;charset=UTF-8" };
    if (config === PostHeadersType.form) {
      headers = { "Content-Type": "multipart/form-data" };
    } else if (config === PostHeadersType.formurlencoded) {
      headers = { "Content-Type": "application/x-www-form-urlencoded" };
      data = qs.stringify(data) as any; // 使用 qs 库来序列化 data
    }
    return instance.post<ApiResult<T>>(url, data, { headers }) as unknown as Promise<ApiResult<T>>;
  },
  put<T>(url: string, data: any): Promise<AxiosResponse<ApiResult<T>, any>> {
    return instance.put<ApiResult<T>>(url, data);
  },
  delete<T>(url: string): Promise<AxiosResponse<ApiResult<T>, any>> {
    return instance.delete<ApiResult<T>>(url);
  },
};
